package com.ouyunc.user.controller;


import com.alibaba.fastjson2.JSON;
import com.ouyunc.common.base.ResponseResult;
import com.ouyunc.im.domain.ImGroup;
import com.ouyunc.user.entity.dto.ImUserDTO;
import com.ouyunc.user.entity.dto.OfflineContent;
import com.ouyunc.user.service.ImGroupService;
import com.ouyunc.user.service.ImUserService;
import com.ouyunc.web.annotation.CurrentLoginUser;
import com.ouyunc.web.common.LoginUser;
import io.swagger.annotations.*;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author fzx
 */
@Api(tags = "用户相关api")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private ImUserService imUserService;


    @Resource
    private ImGroupService imGroupService;

    @ApiOperation("获取当前登录人信息")
    @GetMapping("/current-login-user")
    public ResponseResult currentLoginUser(@CurrentLoginUser LoginUser loginUser) {
        return ResponseResult.success(loginUser.principle());
    }

    @ApiOperation("根据用户id获取用户信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id",dataType = "string", required = true, paramType = "path")})
    @GetMapping("/{userId}")
    public ResponseResult getUser(@PathVariable("userId") String userId) {
        return ResponseResult.success(imUserService.getUser(userId));
    }


    @ApiOperation("根据好友用户id获取好友信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id",dataType = "string", required = true, paramType = "path")})
    @GetMapping("/friends/{friendId}")
    public ResponseResult getFriend(@PathVariable("friendId") String friendId, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.getFriend(userId, friendId));
    }



    @ApiOperation("根据群组id获取群组信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "groupId", value = "群组id",dataType = "string", required = true, paramType = "path")})
    @GetMapping("/groups/{groupId}")
    public ResponseResult getGroup(@PathVariable("groupId") String groupId, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imGroupService.getGroup(userId,groupId));
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ResponseResult register(@ApiParam(name = "imUser", value = "用户注册dto", allowMultiple = true) @RequestBody ImUserDTO imUser) {
        imUserService.register(imUser);
        return ResponseResult.success();
    }

    @ApiOperation("创建群")
    @PostMapping("/create-group")
    public ResponseResult createGroup(@ApiParam(value = "imGroup", name = "im 群信息") @RequestBody ImGroup imGroup, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imGroupService.createGroup(userId, imGroup));
    }

    @ApiOperation("群主设置或取消群管理员")
    @PostMapping("/group-manager/add-cancel")
    public ResponseResult cancelGroupManager(@RequestParam("groupId") String groupId, @RequestParam("originManagerUserId") String originManagerUserId, @RequestParam("isManager") Integer isManager, @CurrentLoginUser LoginUser loginUser) {
        return ResponseResult.success(imGroupService.cancelGroupManager(groupId, originManagerUserId, isManager));
    }

    @ApiOperation("搜索用户/群组信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "searchType", value = "搜索类型: 1-好友搜索，2-群组搜索",dataType = "int", required = true, paramType = "query"),@ApiImplicitParam(name = "username", value = "用户名/用户手机号/用户id/群id/群组名", required = true, paramType = "query")})
    @GetMapping("/search")
    public ResponseResult search(@RequestParam("searchType") Integer searchType, @RequestParam("username") String username) {
        Assert.notNull(searchType, "非法参数！");
        Assert.notNull(username, "非法参数！");
        if (searchType == 1) {
            return ResponseResult.success(imUserService.search(username));
        }
        if (searchType == 2) {
            return ResponseResult.success(imGroupService.search(username));
        }
        return ResponseResult.fail("非法搜索类型！");
    }


    @ApiOperation("获取新朋友通知列表")
    @GetMapping("/new-friend/notify-list")
    public ResponseResult newFriendsNotifyList(@CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.newFriendsNotifyList(userId));
    }

    @ApiOperation("获取群通知列表")
    @GetMapping("/group/notify-list")
    public ResponseResult groupNotifyList(@CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.groupNotifyList(userId));
    }


    @ApiOperation("判断当前登录人和 to 是否是好友")
    @ApiImplicitParams({@ApiImplicitParam(name = "to", value = "消息接收者",dataType = "string", required = true, paramType = "query")})
    @GetMapping("/friend/exist")
    public ResponseResult existFriend(@RequestParam("to") String to, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.existFriend(userId, to));
    }


    @ApiOperation("判断identity是否已经在群组中")
    @ApiImplicitParams({@ApiImplicitParam(name = "identity", value = "要加入群的用户",dataType = "string", required = true, paramType = "query"),@ApiImplicitParam(name = "groupId", value = "群id",dataType = "string", required = true, paramType = "query")})
    @GetMapping("/group/exist")
    public ResponseResult existGroup(@RequestParam("identity") String identity, @RequestParam("groupId") String groupId) {
        return ResponseResult.success(imUserService.existGroup(identity, groupId));
    }

    @ApiOperation("获取当前会话id的最后一个处理消息包的处理状态")
    @ApiImplicitParams({@ApiImplicitParam(name = "sessionId", value = "群请求会话Id",dataType = "string", required = true, paramType = "query"),@ApiImplicitParam(name = "groupId", value = "群id",dataType = "string", required = true, paramType = "query")})
    @GetMapping("/group/session/is-handled")
    public ResponseResult sessionHandler(@RequestParam("sessionId") String sessionId, @RequestParam("groupId") String groupId) {
        return ResponseResult.success(imUserService.sessionHandler(sessionId, groupId));
    }

    @ApiOperation("获取当前联系人列表")
    @GetMapping("/contact-list")
    public ResponseResult contactList(@CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.contactList(userId));
    }

    @ApiOperation("获取临时聊天联系人列表（包括群组）")
    @GetMapping("/temp/chat-list")
    public ResponseResult tempChatList(@CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.tempChatList(userId));
    }

    @ApiOperation("获取联系人的在线状态（不包含群组）")
    @GetMapping("/contact/online")
    public ResponseResult contactOnline(@CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.contactOnline(userId));
    }


    @ApiOperation("添加临时聊天联系人（包括群组）")
    @PostMapping("/temp/chat-list")
    public ResponseResult addTempChat(@RequestParam("from") String from, @RequestParam("to") String to, @RequestParam("userType") Integer userType) {
        return ResponseResult.success(imUserService.addTempChat(from, to, userType));
    }


    @ApiOperation("删除临时聊天联系人（包括群组）")
    @PostMapping("/temp/chat/delete")
    public ResponseResult deleteTempChat(@RequestParam("identity") String identity, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.deleteTempChat(userId, identity));
    }

    @ApiOperation("获取群成员信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "groupId", value = "群id",dataType = "string", required = true, paramType = "query"),@ApiImplicitParam(name = "userId", value = "用户id",dataType = "string", required = true, paramType = "query")})
    @GetMapping("/group-member")
    public ResponseResult groupMember(@RequestParam("groupId") String groupId, @RequestParam("userId") String userId) {
        return ResponseResult.success(imUserService.groupMember(groupId, userId));
    }

    @ApiOperation("获取群成员列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "groupId", value = "群id",dataType = "string", required = true, paramType = "query")})
    @GetMapping("/group-members")
    public ResponseResult groupMembers(@RequestParam("groupId") String groupId) {
        return ResponseResult.success(imUserService.groupMembers(groupId));
    }

    @ApiOperation("修改好友或群在自己这里所显示的昵称备注")
    @ApiImplicitParams({@ApiImplicitParam(name = "identity", value = "好友id/群id",dataType = "string", required = true, paramType = "query"), @ApiImplicitParam(name = "nicknameRemark", value = "昵称备注",dataType = "string", required = true, paramType = "query"), @ApiImplicitParam(name = "userType", value = "用户类型：1-用户，2-群组",dataType = "int", required = true, paramType = "query"), @ApiImplicitParam(name = "type", value = "标识修改群昵称还是用户在群中的昵称：1-群昵称，2-用户在群的昵称",dataType = "int", required = true, paramType = "query")})
    @PostMapping("/nick-name")
    public ResponseResult updateNickname(@RequestParam("identity") String identity, @RequestParam("nicknameRemark") String nicknameRemark, @RequestParam("userType") Integer userType, @RequestParam("type") Integer type, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.updateNickName(identity, nicknameRemark, userType,type, userId));
    }



    @ApiOperation("获取当前群组列表")
    @GetMapping("/group-list")
    public ResponseResult groupList(@CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.groupList(userId));
    }



    @ApiOperation("屏蔽当前登录人的好友")
    @ApiImplicitParams({@ApiImplicitParam(name = "friendId", value = "好友Id",dataType = "string", required = true, paramType = "path"),@ApiImplicitParam(name = "isShield", value = "是否屏蔽：0未屏蔽，1-屏蔽",dataType = "int", required = true, paramType = "query")})
    @PostMapping("/friends/{friendId}/shield")
    public ResponseResult shieldFriend(@PathVariable("friendId") String friendId, @RequestParam("isShield") Integer isShield, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.shieldFriend(userId, friendId, isShield));
    }


    @ApiOperation("将userId拉入当前登录人的黑名单/或解除黑名单")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户Id",dataType = "string", required = true, paramType = "path"),@ApiImplicitParam(name = "join", value = "加入或解除黑名单：0-解除，1-加入",dataType = "int", required = true, paramType = "query")})
    @PostMapping("/{userId}/blacklist")
    public ResponseResult userJoinBlacklist(@PathVariable("userId") String userId, @RequestParam("join") Integer join, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String loginUserId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.userJoinBlacklist(loginUserId, userId, join));
    }

    @ApiOperation("删除当前登录人的好友")
    @PostMapping("/friends/{friendId}/delete")
    public ResponseResult deleteFriend(@PathVariable("friendId") String friendId, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.deleteFriend(userId, friendId));
    }



    @ApiOperation("分页获取聊天历史记录")
    @ApiImplicitParams({@ApiImplicitParam(name = "identity", value = "好友或群id",dataType = "string", required = true, paramType = "path"),@ApiImplicitParam(name = "userType", value = "用户类型：1-用户，2-群组",dataType = "int", required = true, paramType = "query"),@ApiImplicitParam(name = "pageNum", value = "第几页", dataType = "int", paramType = "query"), @ApiImplicitParam(name = "pageSize", dataType = "int", value = "页面数据大小",  paramType = "query"), @ApiImplicitParam(name = "total", dataType = "int", value = "拉取总数据，首次进来会计算一个总数据",  paramType = "query")})
    @GetMapping("/chat/history-record")
    public ResponseResult chatHistoryRecord(@RequestParam("identity") String identity,@RequestParam("userType") Integer userType,@RequestParam(defaultValue = "0", required = false) Integer pageNum, @RequestParam(defaultValue = "20", required = false) Integer pageSize, @RequestParam(defaultValue = "0", required = false) Integer total, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.chatHistoryRecord(userId, identity, userType,pageNum, pageSize,total));
    }


    @ApiOperation("获取取离线未读消息")
    @GetMapping("/chat/offline-unread-record")
    public ResponseResult chatOfflineUnreadRecord(@CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.pullOfflineUnreadMessage(userId));
    }

    @ApiOperation("分页拉取离线消息")
    @GetMapping("/chat/offline-record")
    public ResponseResult chatOfflineRecord(@RequestBody OfflineContent offlineContent, @CurrentLoginUser LoginUser loginUser) {
        Object principle = loginUser.principle();
        String userId = JSON.parseObject(JSON.toJSONString(principle)).getJSONObject("userDetail").getString("id");
        return ResponseResult.success(imUserService.pullOfflineMessage(userId, offlineContent));
    }

}
